class Article < ActiveRecord::Base
  acts_as_taggable
  acts_as_textiled :body
  
  has_many :comments, :dependent => :destroy, :order => 'created_at'
  belongs_to :user
  belongs_to :blog
  
  validates_presence_of :title, :body, :user, :blog

  def self.find_recent(offset, limit)
    Article.find(:all, :order => 'created_at DESC', :offset => offset, :limit => limit)
  end

  def self.find_per_blog(blog_id, offset, limit)
    Article.find(:all, :conditions => ["blog_id = ?", blog_id],
                 :order => 'created_at DESC', :offset => offset, :limit => limit)
  end
  
  def self.find_per_user(user_id, offset, limit)
    Article.find(:all, :conditions => ["user_id = ?", user_id],
                 :order => 'created_at DESC', :offset => offset, :limit => limit)
  end
  
  def self.find_per_user_blog(user, blog_id, offset, limit)
    Article.find(:all, :conditions => ["blog_id = ? and user_id = ?", blog_id, user],
                 :order => 'created_at DESC', :offset => offset, :limit => limit)
  end

  def self.find_per_tag(tag, offset, limit)
    Article.find_tagged_with(tag.name, {:order => "articles.created_at DESC", 
                                        :offset => offset, :limit => limit})
  end  

  def self.count_per_blog(blog_id)
    Article.count(:conditions => ["blog_id = ?", blog_id])
  end  
  
  def self.count_per_user(user_id)
    Article.count(:conditions => ["user_id = ?", user_id])
  end  
  
  def self.count_per_user_blog(user, blog_id)
    Article.count(:conditions => ["blog_id = ? and user_id = ?", blog_id, user])
  end  

  # find a random article
  # URL: /articles/random, /articles/random.xml etc.
  # http://weblog.jamisbuck.org/2006/10/7/helping-activerecord-finders-help-you
  def self.find(*args)
    if args.first.to_s == "random"
      ids = connection.select_all("SELECT id FROM articles")
      super(ids[rand(ids.length)]["id"].to_i)
    else
      super
    end
  end
end
